package com.study.common.baidu.map;

import com.study.common.baidu.map.domain.BaiduMapInverseResponse;
import com.study.common.baidu.map.domain.BaiduMapPolymerizationResponse;
import com.study.common.baidu.map.domain.Location;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * 百度地图工具类
 */
@Slf4j
@Component
public class MapToolsUtils {

    /**
     * 百度地图:地理编码调用接口地址: Get请求
     */
    private static final String polymerization = "https://api.map.baidu.com/geocoding/v3";

    /**
     * 百度地图:全球逆地理编码地址: Get请求
     */
    private static final String inverseAddress = "https://api.map.baidu.com/reverse_geocoding/v3/";

    /**
     * 百度地图服务AK
     */
    private static final String ak = "Bg2lKxxOeBcwojKLNrzOzRoQGaqpm4dp";

    //坐标类型包括：bd09ll（百度经纬度坐标）、bd09mc（百度米制坐标）、gcj02ll（国测局经纬度坐标，仅限中国）、wgs84ll（ GPS经纬度）
    private static final String bd09ll = "bd09ll";

    private static final String bd09mc = "bd09mc";

    private static final String gcj02ll = "gcj02ll";

    private static final String wgs84ll = "wgs84ll";


    /**
     * 根据当前地理位置反编译出Gps点
     *
     * @param address
     * @return
     */
    public String getAddressGps(String address) {

        RestTemplate restTemplate = createRestTemplateConverter();

        String url = polymerization + "?address=" + address + "&output=" + "json" + "&ak=" + ak;

        ResponseEntity<BaiduMapPolymerizationResponse> response = restTemplate.exchange(url, HttpMethod.GET,
                null, BaiduMapPolymerizationResponse.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            BaiduMapPolymerizationResponse body = response.getBody();

            if (body.getStatus() != 0) {
                log.error("当前物理地址转换gps点失败,请检查具体信息是否有误");
                throw new RuntimeException("当前物理地址转换gps点失败,请检查具体信息是否有误");
            }
            Location location = body.getResult().getLocation();
            return location.getLng() + "," + location.getLat();
        }
        return null;
    }


    /**
     * 根据Gps点位置检索物理地址
     *
     * @param longitude 经度
     * @param latitude  纬度
     * @param language  语言标识
     * @return 返回当前经度的地址
     */
    public String getAddress(double longitude, double latitude, String language) {

        RestTemplate restTemplate = createRestTemplateConverter();

        String url = inverseAddress + "?ak=" + ak + "&output=" + "json" + "&coordtype=" + wgs84ll + "&location=" + latitude + "," + longitude + "&language=" + language;

        ResponseEntity<BaiduMapInverseResponse> response = restTemplate.exchange(url, HttpMethod.GET,
                null, BaiduMapInverseResponse.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            BaiduMapInverseResponse body = response.getBody();

            if (body.getStatus() != 0) {
                log.error("当前请求gps点转换物理地址失败,请检查具体信息是否有误");
                return null;
            }

            String formattedAddress = body.getResult().getFormatted_address();
            if (formattedAddress != null) {
                return formattedAddress;
            }
            return null;

        }

        return null;
    }






    /**
     * 手动创建了一个 RestTemplate 实例，并将 MappingJackson2HttpMessageConverter 添加为消息转换器。然后，我们将其设置为支持处理 application/json 类型的响应
     *
     * @return
     */
    private static RestTemplate createRestTemplateConverter() {
        RestTemplate restTemplate = new RestTemplate();

        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setSupportedMediaTypes(MediaType.parseMediaTypes("text/javascript;charset=utf-8"));
        List<HttpMessageConverter<?>> converters = new ArrayList<>();
        converters.add(converter);
        restTemplate.setMessageConverters(converters);
        return restTemplate;
    }


    public static void main(String[] args) {
        MapToolsUtils mapToolsUtils = new MapToolsUtils();
        String address = "青海省西宁市城东区南山路中惠机电城A31区7号";
        String addressGps = mapToolsUtils.getAddressGps(address);

//        String address1 = mapToolsUtils.getAddress(121.49884033194, 31.225696563611, "zh-CN");
//        System.out.println("address1 = " + address1);
        System.out.println("addressGps = " + addressGps);
    }

}
